package com.chookss.home.search.fragment;


import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Html;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.SimpleItemAnimator;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.chookss.R;
import com.chookss.Urls;
import com.chookss.home.entity.SearchEntity;
import com.chookss.home.myTest.MyTestsDetailActivity;
import com.chookss.home.search.entity.SearchAllEntity;
import com.chookss.tiku.AnswerExamActivity;
import com.chookss.tiku.ExamResultActivitys;
import com.chookss.tiku.entity.MyExam;
import com.chookss.tools.ClearMoreZeroUtil;
import com.chookss.tools.MyEvent;
import com.chookss.tools.MyToast;
import com.chookss.tools.NavigationTools;
import com.chookss.tools.SignUtils2;
import com.chookss.tools.Utils;
import com.chookss.tools.okgoconfig.MyHttpRequest;
import com.chookss.tools.okgoconfig.callback.ObserverCallback;
import com.chookss.tools.okgoconfig.model.LzyResponse;
import com.chookss.view.DrawableTextView;
import com.chookss.view.RecycleViewDivider;
import com.google.gson.reflect.TypeToken;
import com.johnrambo.ktea.common.klogutil.KLog;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.constant.RefreshState;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import io.reactivex.annotations.NonNull;
import io.reactivex.annotations.Nullable;

@SuppressLint("ValidFragment")
public class SearchTestFragment extends SearchBaseFragment {

    public Context mContext;
    Unbinder unbinder;
    @BindView(R.id.srlView)
    SmartRefreshLayout srlView;
    @BindView(R.id.rvView)
    RecyclerView rv;
    @BindView(R.id.llNone)
    LinearLayout llNone;
    @BindView(R.id.tvNone)
    TextView tvNone;
    private MyTestAdapter adapter;
    private List<SearchAllEntity.ExamBean.ListBean> list = new ArrayList<>();
    private int currentPage = 1;
    private String pageSize = "20";
    private boolean isEnd = false;//是否到底
    private boolean isTest = false;//是否有正在进行的考试
    private int index = -1;//正在进行考试的下标
    private Timer mTimer = null;
    private TimerTask mTimerTask = null;
    private String localKey = "", localType = "0";

    public SearchTestFragment() {

    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = getActivity();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_search_base, container, false);
        unbinder = ButterKnife.bind(this, view);
        init();
        return view;
    }

    @Override
    public void onViewStateRestored(@androidx.annotation.Nullable Bundle savedInstanceState) {
        super.onViewStateRestored(savedInstanceState);
    }

    private void init() {
        rv.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.VERTICAL, false));
        rv.addItemDecoration(new RecycleViewDivider(mContext, LinearLayoutManager.HORIZONTAL, Utils.dip2px(mContext, 0.5f), getResources().getColor(R.color.line_gray)));
        adapter = new MyTestAdapter(R.layout.item_search_test_list, mContext, list);
        rv.setAdapter(adapter);
        rv.getItemAnimator().setAddDuration(0);
        rv.getItemAnimator().setChangeDuration(0);
        rv.getItemAnimator().setMoveDuration(0);
        rv.getItemAnimator().setRemoveDuration(0);
        ((SimpleItemAnimator) rv.getItemAnimator()).setSupportsChangeAnimations(false);
        rv.setItemAnimator(null);
        srlView.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                if (isEnd) {//has next page
                    MyToast.show("没有更多数据了");
                    loadEnd();
                } else {
                    currentPage++;
                    getData();
                }
            }
        });
        srlView.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshLayout) {
                isEnd = false;
                currentPage = 1;
                index = -1;
                isTest = false;
                getData();
                srlView.setEnableRefresh(false);
            }
        });
    }

    @Override
    public void onVisible() {
        super.onVisible();
        if(srlView==null){
            return;
        }
        if (Utils.isNull(localKey)) {
            srlView.autoRefresh();
        } else {
            srlView.setEnableRefresh(true);
            srlView.autoRefresh();
        }

    }

    @Override
    public void refreshData() {
        if(srlView==null){
            return;
        }
        srlView.setEnableRefresh(true);
        srlView.autoRefresh();
    }

    private void getData() {
        isTest = false;
        localKey = key;
        localType = searchType;
        Map<String, String> map = new HashMap<>();
        map.put("pageNum", currentPage + "");
        map.put("pageSize", pageSize + "");
        map.put("word", key);
        map.put("searchType", searchType);
        map.put("itemType", "exam");
        KLog.i(key + "------");
        MyHttpRequest.getDefault().getRequest(new TypeToken<LzyResponse<SearchAllEntity>>() {
        }.getType(), null, Urls.selectForSearch, SignUtils2.makeSignStr(map), false, new ObserverCallback<SearchAllEntity>() {
            @Override
            public void onSuccess(SearchAllEntity data) {
                if (currentPage == 1) {
                    list.clear();
                    adapter.notifyDataSetChanged();
                }
                loadEnd();
                if(srlView==null||llNone==null){
                    return;
                }
                if (data.getExam() == null) {
                    isEnd = true;
                    if (list.size() == 0) {
                        srlView.setVisibility(View.GONE);
                        llNone.setVisibility(View.VISIBLE);
                        String init = "抱歉，没用找到关于“<font color='#666666'>" + key + "</font>”的考试";
                        tvNone.setText(Html.fromHtml(init));
                    }
                    return;
                }
                if (data.getExam().getList() != null && data.getExam().getList().size() > 0) {
                    for (int i = 0; i < data.getExam().getList().size(); i++) {
                        if ("3".equals(data.getExam().getList().get(i).getExamStatus())) {
                            isTest = true;
                            allTime = Utils.changeNumber(data.getExam().getList().get(i).getSeconds());
                            index = list.size() + i;
                            startTimer();
                        }
                    }
                    list.addAll(data.getExam().getList());
                    adapter.notifyDataSetChanged();
                    srlView.setVisibility(View.VISIBLE);
                    llNone.setVisibility(View.GONE);
                } else {
                    isEnd = true;
                    if (list.size() == 0) {
                        srlView.setVisibility(View.GONE);
                        llNone.setVisibility(View.VISIBLE);
                        String init = "抱歉，没用找到关于“<font color='#666666'>" + key + "</font>”的考试";
                        tvNone.setText(Html.fromHtml(init));
                    }
                }

            }

            @Override
            public void onError(String errorMsg) {
                loadEnd();
                MyToast.show(Utils.onErrorTips(errorMsg));
            }
        });
    }

    @Override
    public void initImmersionBar() {

    }

    class MyTestAdapter extends BaseQuickAdapter<SearchAllEntity.ExamBean.ListBean, BaseViewHolder> {
        private Context context;
        private int type;

        public MyTestAdapter(int layoutResId, Context context, @Nullable List<SearchAllEntity.ExamBean.ListBean> data) {
            super(layoutResId, data);
            this.context = context;
        }

        @Override
        protected void convert(BaseViewHolder helper, SearchAllEntity.ExamBean.ListBean item) {
            TextView tvTitle = helper.getView(R.id.tvTitle);
            TextView tvSeconds = helper.getView(R.id.tvSeconds);
            TextView tvScore = helper.getView(R.id.tvScore);
            DrawableTextView tvTime = helper.getView(R.id.tvTime);
            TextView tvTimeLength = helper.getView(R.id.tvTimeLength);
            TextView tvInit = helper.getView(R.id.tvInit);
            TextView tvPublishTime = helper.getView(R.id.tvPublishTime);
            TextView tvContinue = helper.getView(R.id.tvContinue);
            TextView tvStatus = helper.getView(R.id.tvStatus);
            TextView tvExamineeName = helper.getView(R.id.tvExamineeName);
            TextView tvExamPublishName = helper.getView(R.id.tvExamPublishName);
            //考试状态  0 缺考 1 未完成(101 考试尚未开始 102 考试已经开始) 2 已完成 3进行中

            if ("3".equals(item.getExamStatus())) {
                tvContinue.setVisibility(View.VISIBLE);
                tvStatus.setVisibility(View.GONE);
                tvSeconds.setVisibility(View.VISIBLE);
                tvScore.setVisibility(View.GONE);
                tvSeconds.setTextColor(Color.parseColor("#E12416"));
                tvSeconds.setBackgroundResource(R.color.white);
                tvSeconds.setText("剩余" + Utils.changeSeconds(Utils.changeNumber(item.getSeconds())));
            } else if ("0".equals(item.getExamStatus())) {
                tvContinue.setVisibility(View.GONE);
                tvStatus.setVisibility(View.VISIBLE);
                tvSeconds.setVisibility(View.VISIBLE);
                tvScore.setVisibility(View.GONE);
                tvSeconds.setTextColor(Color.parseColor("#999999"));
                tvSeconds.setBackgroundResource(R.color.white);
                tvStatus.setText("查看试卷");
                tvSeconds.setText("缺考");
            } else if ("101".equals(item.getExamStatus())) {
                tvContinue.setVisibility(View.GONE);
                tvStatus.setVisibility(View.VISIBLE);
                tvSeconds.setVisibility(View.VISIBLE);
                tvScore.setVisibility(View.GONE);
                tvSeconds.setTextColor(Color.parseColor("#FCA817"));
                tvSeconds.setBackgroundResource(R.color.white);
                tvStatus.setText("等待考试");
                tvSeconds.setText(Utils.getExamTime(item.getSeconds()) + "后开考");
            } else if ("102".equals(item.getExamStatus())) {
                tvContinue.setVisibility(View.GONE);
                tvStatus.setVisibility(View.VISIBLE);
                tvSeconds.setVisibility(View.VISIBLE);
                tvScore.setVisibility(View.GONE);
                tvSeconds.setTextColor(Color.parseColor("#00C993"));
                tvSeconds.setBackgroundResource(R.color.white);
                tvStatus.setText("进入考场");
                tvSeconds.setText(Utils.getExamTime(item.getSeconds()) + "后结束");
            } else if ("2".equals(item.getExamStatus())) {
                tvContinue.setVisibility(View.GONE);
                tvStatus.setVisibility(View.VISIBLE);
                tvSeconds.setVisibility(View.GONE);
                tvScore.setVisibility(View.VISIBLE);
                tvStatus.setText("查看试卷");
                tvScore.setText(ClearMoreZeroUtil.subZeroAndDot(item.getScore()) + "分");
            }
            tvTitle.setText(Utils.matcherSearchTitle(context.getResources().getColor(R.color.main_color), item.getExamName(), localKey));
            tvTime.setText("有效期：" + Utils.clearZeroTimes(item.getStartTime()) + "-" + Utils.clearZeroTimes(item.getEndTime()));
            tvTimeLength.setText("考试时长：" + item.getExamTimeLength() + "分钟");

            if (Utils.isNull(item.getExamDetail())) {
                tvInit.setVisibility(View.GONE);
            } else {
                tvInit.setText("备注：" + item.getExamDetail());
                tvInit.setVisibility(View.VISIBLE);
            }
            tvPublishTime.setText("发布时间：" + item.getCreateTime());
            if (Utils.isNull(item.getEmployeeNames())) {
                tvExamineeName.setVisibility(View.GONE);
            } else {
                tvExamineeName.setVisibility(View.VISIBLE);
                tvExamineeName.setText("考生：");
                tvExamineeName.append(Utils.matcherSearchTitle(context.getResources().getColor(R.color.main_color), item.getEmployeeNames(), key));
            }
            if (Utils.isNull(item.getCreateEmployeeName())) {
                tvExamPublishName.setVisibility(View.GONE);
            } else {
                tvExamPublishName.setVisibility(View.VISIBLE);
                tvExamPublishName.setText("创建人：");
                tvExamPublishName.append(Utils.matcherSearchTitle(context.getResources().getColor(R.color.main_color), item.getCreateEmployeeName(), key));
            }
            tvContinue.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (Urls.antiShake.check()) {
                        return;
                    }
                    MyExam myExam = Utils.modelA2B(item);
                    Intent intent = new Intent(mContext, AnswerExamActivity.class);
                    intent.putExtra("answerType", "1");
                    intent.putExtra("exam", myExam);
                    startActivity(intent);
                }
            });
            tvStatus.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (Urls.antiShake.check()) {
                        return;
                    }
                    NavigationTools.saveUseRecord(mContext,"1","05");
                    //考试状态  0 缺考 1 未完成(101 考试尚未开始 102 考试已经开始) 2 已完成 3进行中
                    MyExam myExam = Utils.modelA2B(item);
                    if ("101".equals(item.getExamStatus())) {
                        Intent intent = new Intent(mContext, MyTestsDetailActivity.class);
                        intent.putExtra("examCode", item.getExamCode());
                        intent.putExtra("recordType", "4");
                        intent.putExtra("examStatus", item.getExamStatus());
                        intent.putExtra("exam", myExam);
                        startActivity(intent);
                    } else if ("102".equals(item.getExamStatus())) {
                        if (isTest) {
                            MyToast.show("请先完成正在进行的考试");
                            return;
                        }
                        Intent intent = new Intent(mContext, MyTestsDetailActivity.class);
                        intent.putExtra("examCode", item.getExamCode());
                        intent.putExtra("examStatus", item.getExamStatus());
                        intent.putExtra("recordType", "4");
                        intent.putExtra("exam", myExam);
                        startActivity(intent);
                    } else if ("3".equals(item.getExamStatus())) {
                        Intent intent = new Intent(mContext, AnswerExamActivity.class);
                        intent.putExtra("answerType", "1");
                        intent.putExtra("exam", myExam);
                        startActivity(intent);
                    } else if ("2".equals(item.getExamStatus())) {
                        Intent intent = new Intent(mContext, ExamResultActivitys.class);
                        intent.putExtra("recordType", "4");
                        intent.putExtra("pmKey", item.getRecordUid());
                        intent.putExtra("examCode", item.getExamCode());
                        intent.putExtra("examName", item.getExamName());
                        startActivity(intent);
                    } else if ("0".equals(item.getExamStatus())) {
                        Intent intent = new Intent(mContext, ExamResultActivitys.class);
                        intent.putExtra("recordType", "4");
                        intent.putExtra("pmKey", item.getExamCode());
                        intent.putExtra("isMiss", 1);
                        intent.putExtra("examCode", item.getExamCode());
                        intent.putExtra("examName", item.getExamName());
                        startActivity(intent);
                    }
                }
            });
        }
    }

    private void loadEnd() {
        if (null != srlView && srlView.getState() == RefreshState.Refreshing)
            srlView.finishRefresh(true);
        if (null != srlView && srlView.getState() == RefreshState.Loading)
            srlView.finishLoadMore(true);
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
        stopTimer();
    }

    private void startTimer() {
        if (mTimer == null) {
            mTimer = new Timer();
        }
        if (mTimerTask == null) {
            mTimerTask = new TimerTask() {
                @Override
                public void run() {
                    //每分中上传数据
                    Message message = new Message();
                    message.what = 1;
                    handler.sendMessage(message);
                }
            };
            if (mTimer != null && mTimerTask != null) {
                mTimer.schedule(mTimerTask, 1000, 1000);//执行定时器中的任务
            }
        }

    }

    private int allTime = 0;
    // handler类接收数据
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 1) {
                allTime--;
                if (isTest) {
                    if (allTime == -1) {
                        isEnd = false;
                        currentPage = 1;
                        getData();
                    } else if (allTime >= 0) {
                        if (list != null && list.size() > index) {
                            list.get(index).setSeconds(allTime + "");
                            adapter.notifyItemChanged(index);
                        }
                    }
                }
            }
        }

    };

    /**
     * 停止定时器，初始化定时器开关
     */
    private void stopTimer() {
        if (mTimer != null) {
            mTimer.cancel();
            mTimer = null;
        }
        if (mTimerTask != null) {
            mTimerTask.cancel();
            mTimerTask = null;
        }
    }
}
